package com.heima.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 基本搜索业务
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
       //TODO
        //校验参数
        if (dto==null){
            ResponseResult.errorResult(501, "参数失效");
        }
        //构建查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title")
                .field("content")
                .defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        //分页和排序
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.must(rangeQueryBuilder);
        sourceBuilder.from(0).size(dto.getPageSize()).sort("publishTime", SortOrder.DESC);
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<from style='color:red; font-size:inherit;'>");
        highlightBuilder.postTags("</from>");
        sourceBuilder.highlighter(highlightBuilder);

        sourceBuilder.query(boolQueryBuilder);
        searchRequest.source(sourceBuilder);
        //解析响应结果
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            List<Map> mapList = new ArrayList<>();
            for (SearchHit hit : response.getHits().getHits()) {
                String json = hit.getSourceAsString();
                Map map = JSON.parseObject(json, Map.class);

                if (CollUtil.isNotEmpty(hit.getHighlightFields())){
                    Text[] titles = hit.getHighlightFields().get("title").getFragments();
                    String title = StringUtils.join(titles);
                    map.put("h_title", title);
                }else {
                    map.put("h_title", map.get("title"));
                }
                mapList.add(map);
            }

            return ResponseResult.okResult(mapList);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 自动补全功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(UserSearchDto dto) {
       //TODO
        return null;
    }
}
